# coding=utf-8

from sqlserver import *
import pymysql
import datetime

#

consistence_file='/home/marvin/daily_job/py_job/consistence'
# consistence_file = 'consistence'
now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
before = (now + datetime.timedelta(days=-3, hours=-0.5)).strftime("%Y-%m-%d")  ##c为str（即字符串），将时间格式化成字符串
print today, before
host = '192.168.0.31'
port = 3306
dbname = 'sqlserver'
user = 'root'
passwd = 'root'
sql1 = '''
   select station_id,COUNT(1) from transactions as Z where
   Z.transaction_date>='%s'
   and Z.transaction_date<'%s'
   GROUP BY station_id
     '''
sql2 = '''
     select COUNT(1) from transactions as Z where
     Z.transaction_date>='%s'
     and Z.transaction_date<'%s'
       '''
sql1 = sql1 % (before, today)
sql2 = sql2 % (before, today)


def doCheck():
    db = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=dbname, charset='utf8')
    cur = db.cursor()
    cur.execute(sql1)
    middb_data = cur.fetchall()
    middb_data = dict(middb_data)
    cur.close()
    flag = False
    for k in sqlserver.keys():
        try:
            count1 = middb_data.get(k,0.0)
            ms = ODBC_MS('{SQL SERVER}', sqlserver.get(k)[1], 'enablerdb', sqlserver.get(k)[2],
                         sqlserver.get(k)[3])
            count2 = ms.ExecQuery(sql2)[0][0]
            if count2 == count1:
                print 'check station=%s,no problem!!!  detail:sqlserv:%d,middb:%d' % (k, count2, count1)
            else:
                print 'warning station=%s!!!!!!!!!!!  detail:sqlserv:%d,middb:%d' % (k, count2, count1)
                flag = True
        except:
            print 'Exception!!!!!!!  station=' + str(k)

        # 发现数据不一致，发送邮件
    if flag:
        with open(consistence_file, 'w') as f:
            f.write('1')
    else:
        with open(consistence_file, 'w') as f:
            f.write('0')


if __name__ == '__main__':
    doCheck()
